//
//  BiSaleApplyViewController.m
//  TrunkIndustryManageSystem
//
//  Created by WT_lyy on 15/4/21.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiSaleApplyViewController.h"
#import "BiSaleListViewController.h"
#import "BiDatePickerView.h"

#import "BiIndexSaleViewController.h"

static CGRect frame;
@interface BiSaleApplyViewController ()<UITextFieldDelegate,UITextViewDelegate,UITableViewDataSource,UITableViewDelegate,BiDatePickerViewDelegate>{

   __strong IBOutlet UIView *_cartypeBgView;
    
    __weak IBOutlet UIScrollView *_scrollView;
    
    __weak IBOutlet UITableView * _carTypeTable;
    
    BiDatePickerView * _datePickerView;
    
    NSInteger carType;
    
    int dateType;  //1为出发时间，2为返回时间
}

@property (weak, nonatomic) IBOutlet UILabel *labAppler;
@property (weak, nonatomic) IBOutlet UILabel *labcarType;
@property (weak, nonatomic) IBOutlet UILabel *labStarttime;
@property (weak, nonatomic) IBOutlet UILabel *labReturnTime;

@property (weak, nonatomic) IBOutlet UITextField *textfDes;
@property (weak, nonatomic) IBOutlet UITextField *textfCarNum;

@property (weak, nonatomic) IBOutlet UITextField *tetxfCost;
@property (weak, nonatomic) IBOutlet UITextField *textfKilometer;
@property (weak, nonatomic) IBOutlet UITextField *textfJoiner;
@property (weak, nonatomic) IBOutlet UITextView *textvRemark;
@property (weak, nonatomic) IBOutlet UITextView *tetxvReason;
@property (weak, nonatomic) IBOutlet UIButton *btnCartype;
@property (weak, nonatomic) IBOutlet UIButton *btnGooffTime;
@property (weak, nonatomic) IBOutlet UIButton *btnReturnTime;
@end

@implementation BiSaleApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavBackBtn];
    
    [self setNavBarTitle:@"申请行销"];
    
    [self setNavBarWithHidden:NO];

    [self addTestView];
    
    _scrollView.contentSize = CGSizeMake(320, 600);
    
    self.labAppler.text = [BiUserEntity sharedInstance].name;
    
    _scrollView.contentSize = CGSizeMake(MAIN_SCREEN_WIDTH, 524);
    
    [self lableLayerSetting];
    
    _carTypeTable.center = _cartypeBgView.center;
    
    _carTypeTable.rowHeight = 40;
    
    _carTypeTable.layer.cornerRadius = 4;
    
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    
    [self.view addGestureRecognizer:tap];
}

- (void)tapClick{

    [_tetxfCost resignFirstResponder];
    
    [_textfKilometer resignFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    [self dataFill];
}

- (void)dataFill{

    if (self.Centity) {
        
        _labStarttime.text = self.Centity.gooffTime;
        
        _labReturnTime.text = self.Centity.returnTime;
        
        if (self.Centity.useCarType.hash == @"2".hash) {
            _labcarType.text = @"公有";
        }else if (self.Centity.useCarType.hash == @"1".hash){
            _labcarType.text = @"自有";
        }else{
            _labcarType.text = @"无";
        }
        
        _textfJoiner.text = self.Centity.userApplyName;
        
        _textfCarNum.text = self.Centity.licensePlate;
        
        _textfDes.text = self.Centity.destination;

        _tetxfCost.text = [NSString stringWithFormat:@"%@",self.Centity.fee];
        
        _textfKilometer.text = [NSString stringWithFormat:@"%@",self.Centity.kilometre];
        
        _textvRemark.text = self.Centity.remark;
        
        _tetxvReason.text = self.Centity.xingxiaoRejectReason;
        
        _labAppler.text = self.Centity.userApplyName;
    }
}

- (void)lableLayerSetting{
    self.textfDes.layer.cornerRadius = 5;
    self.textfDes.layer.borderWidth = 0.5;
    self.textfDes.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.textfCarNum.layer.cornerRadius = 5;
    self.textfCarNum.layer.borderWidth = 0.5;
    self.textfCarNum.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.tetxfCost.layer.cornerRadius = 5;
    self.tetxfCost.layer.borderWidth = 0.5;
    self.tetxfCost.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.textfKilometer.layer.cornerRadius = 5;
    self.textfKilometer.layer.borderWidth = 0.5;
    self.textfKilometer.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.textfJoiner.layer.cornerRadius = 5;
    self.textfJoiner.layer.borderWidth = 0.5;
    self.textfJoiner.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;

    self.btnGooffTime.layer.borderWidth = 0.5;
    
    self.btnGooffTime.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.btnGooffTime.layer.cornerRadius = 5;
    
    self.btnReturnTime.layer.borderWidth = 0.5;
    
    self.btnReturnTime.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.btnReturnTime.layer.cornerRadius = 5;
    
    self.btnCartype.layer.borderWidth = 0.5;
    
    self.btnCartype.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    
    self.btnCartype.layer.cornerRadius = 5;
    
    self.textvRemark.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    self.textvRemark.layer.borderWidth = 0.5;
    
    self.tetxvReason.layer.borderColor = [UIColor colorWithRed:204.0/255.0 green:204.0/255.0 blue:204.0/255.0 alpha:100.0].CGColor;
    self.tetxvReason.layer.borderWidth = 0.5;
    
    _textfJoiner.frame = CGRectMake(_textfJoiner.frame.origin.x, _textfJoiner.frame.origin.y+3, _textfJoiner.frame.size.width, _textfJoiner.frame.size.height-6);
    _textfCarNum.frame = CGRectMake(_textfCarNum.frame.origin.x, _textfCarNum.frame.origin.y+3, _textfCarNum.frame.size.width, _textfCarNum.frame.size.height-6);
    _textfDes.frame = CGRectMake(_textfDes.frame.origin.x, _textfDes.frame.origin.y+3, _textfDes.frame.size.width, _textfDes.frame.size.height-6);
    
    _tetxfCost.frame = CGRectMake(_tetxfCost.frame.origin.x, _tetxfCost.frame.origin.y+3, _tetxfCost.frame.size.width, _tetxfCost.frame.size.height-6);
    _textfKilometer.frame = CGRectMake(_textfKilometer.frame.origin.x, _textfKilometer.frame.origin.y+3, _textfKilometer.frame.size.width, _textfKilometer.frame.size.height-6);
}


-(void)onNavBackBtnClick{
    
    for (UIViewController * Vctrl in self.navigationController.viewControllers) {
        if ([Vctrl isKindOfClass:[BiIndexSaleViewController class]]) {
            
            [self.navigationController popToViewController:Vctrl animated:YES];
            
            break;
        }
    }
    
}


#pragma -mark  UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{

    if (isIPhone4) {
        
        if (textField == _textfKilometer) {
            
            _scrollView.frame = CGRectMake(0, _scrollView.frame.origin.y - 30, MAIN_SCREEN_WIDTH, _scrollView.frame.size.height);
        }
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

    if (isIPhone4) {
        
        if (textField == _textfKilometer) {
            
            _scrollView.frame = CGRectMake(0, _scrollView.frame.origin.y + 30, MAIN_SCREEN_WIDTH, _scrollView.frame.size.height);
        }
    }
}
#pragma mark -textview delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([@"\n" isEqualToString:text] == YES)
    {
        [textView resignFirstResponder];
        
        
        return NO;
    }
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    frame = _scrollView.frame;
    
    _scrollView.frame = CGRectMake(0, _scrollView.frame.origin.y - 126, _scrollView.frame.size.width, _scrollView.frame.size.height);
    
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    
    _scrollView.frame = frame;
    [textView resignFirstResponder];
    
}

- (void)textInputResignFirstResponser{

    [_textfJoiner resignFirstResponder];
    [_textfCarNum resignFirstResponder];
    [_textfDes resignFirstResponder];
    [_textfKilometer resignFirstResponder];
    [_tetxfCost resignFirstResponder];
    [_textvRemark resignFirstResponder];
    [_tetxvReason resignFirstResponder];
}

#pragma -mark UitabeViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _textfCarNum.enabled = YES;
    [_cartypeBgView removeFromSuperview];
    
    carType = indexPath.row;
    
    if (0 == indexPath.row) {
        _labcarType.text = @"无";
        _textfCarNum.enabled = NO;
    }else if (1 == indexPath.row){
    
         _labcarType.text = @"自有";
    }else if (2 == indexPath.row){
        
        _labcarType.text = @"公有";
    }
    
   
    
}

#pragma -mark UitabeViewDatasource

- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * myIndentifier = @"CartypeCell";
    
    UITableViewCell * cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:myIndentifier];
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myIndentifier];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    UIView * lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 40, 200, 1)];
    
    [cell addSubview:lineV];
    
    lineV.backgroundColor = [UIColor lightGrayColor];
    
    UILabel * lab = GET_LABEL(CGRectMake(0, 12, 200, 16), 14, NO, [UIColor blackColor], NSTextAlignmentCenter);
    
    [cell addSubview:lab];
    
    if (0 == indexPath.row) {
        
        lab.text = @"无";
    }else if (1 == indexPath.row){
    
        lab.text = @"自有";
    }else if (2 == indexPath.row){
        
        lab.text = @"公有";
    }

    return cell;
}



#pragma mark BiDatePickerViewDelegate
- (void)onDatePickerViewDateSelect:(id)sender date:(NSDate*)date
{
    
    [_datePickerView removeFromSuperview];
    
    NSString * dataeStr = [BiUtil stringFromFomate:date formate:@"yyyy-MM-dd hh:mm"];
    
    if (1 == dateType) {
        _labStarttime.text = dataeStr;
        
    }else if (2 == dateType){
    
        _labReturnTime.text = dataeStr;
    }
    
    if (dateType == 2 && isIPhone4) {
        
        _scrollView.frame = CGRectMake(0, _scrollView.frame.origin.y + 100, MAIN_SCREEN_WIDTH, _scrollView.frame.size.height);
    }
    
}

#pragma -mark Btn Action
- (IBAction)btnClick:(UIButton *)sender {
    
    
    if (0 != carType && [BiUtil isBlankString:_textfCarNum.text]) {
        
        [self showMessage:@"车牌号未填写"];
        
        return;
    }
    if (carType!=0 && ![GT_Tool validateCarNo:_textfCarNum.text]) {
        
            
        [self showMessage:@"车牌号未按照正确格式填写"];
        
        return;

    }
    
    if ([BiUtil isBlankString:_textfDes.text]) {
        
        [self showMessage:@"目的地未填写"];
        
        return;
    }
    NSString * gooffStr = _labStarttime.text;
    if ([BiUtil isBlankString:gooffStr]) {
        
        [self showMessage:@"出发时间未选择"];
        
        return;
    }
     NSString * returnStr = _labReturnTime.text;
    if ([BiUtil isBlankString:returnStr]) {
        
        [self showMessage:@"返回时间未选择"];
        
        return;
    }
    
    
    NSDate * goffDate =  [BiUtil dateFromFomate:gooffStr formate:@"yyyy-MM-dd hh:mm"];
    NSDate * returnDate =  [BiUtil dateFromFomate:returnStr formate:@"yyyy-MM-dd hh:mm"];
    if ([returnDate laterDate:goffDate] == goffDate ) {
        
        [self showMessage:@"亲，返回时间早于出发时间"];
        
        return;
    }
    
    if ([BiUtil isBlankString:_tetxfCost.text]) {
        
        [self showMessage:@"预计费用未填写"];
        
        return;
    }
    if ([BiUtil isBlankString:_textfKilometer.text]) {
        
        [self showMessage:@"预计距离未填写"];
        
        return;
    }
    
    
    if (0 == sender.tag) {
        
        NSString * status = @"0";
        
        if (self.Centity) {
            
            status = @"1";
        }
        
        NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"id",
                                  [BiUserEntity sharedInstance].userid,@"userApplyId",
                                  self.textfJoiner.text,@"participant",
                                  self.textfDes.text,@"destination",
                                  _labStarttime.text,@"gooffTime",
                                  [NSString stringWithFormat:@"%d",(int)carType],@"useCarType",
                                  self.textfCarNum.text,@"licensePlate",
                                  _labReturnTime.text,@"returnTime",
                                  self.textfKilometer.text,@"kilometre",
                                  self.tetxfCost.text,@"fee",
                                  self.textvRemark.text,@"remark",
                                  self.tetxvReason.text,@"xingxiaoRejectReason",
                                  status,@"status",
                                  nil];
    
        [[BiNetEngine shareInstance] requestSaleApplySave:self paraDict:paraDic];
        
        [self asyshowHUDView:WAITING CurrentView:self];
        
    }else if(1 == sender.tag){
    
        if (!self.Centity) {
            
            [self showMessage:@"亲，请先保存再审核！"];
            
        }else{
        
//            
//            NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"id",
//                                      [BiUserEntity sharedInstance].userid,@"xingxiaoApproverId",
//                                      [BiUtil stringFromFomate:[NSDate date] formate:@"yyyy-MM-dd hh:mm:ss"],@"xingxiaoApproveTime",
//                                      _tetxvReason.text,@"xingxiaoRejectReason",
//                                      @"1",@"status",
//                                      nil];
            
            NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.Centity.e_id,@"id",
                                      @"1",@"status",
                                      nil];
            
            [[BiNetEngine shareInstance] requestSaleApplyCheck:self paraDict:paraDic];
            
            [self asyshowHUDView:WAITING CurrentView:self];
            
        }
    }
}

- (IBAction)btnInputClick:(UIButton *)sender {
    
    [self textInputResignFirstResponser];
    
    if (10 == sender.tag) {
        
        if (_carTypeTable) {

            
            [self.view.window addSubview:_cartypeBgView];
        }
        
    }else{
    
        dateType = (int)sender.tag - 10;
        
        if (dateType == 2 && isIPhone4) {
            
            _scrollView.frame = CGRectMake(0, _scrollView.frame.origin.y - 100, MAIN_SCREEN_WIDTH, _scrollView.frame.size.height);
        }
        
        if (!_datePickerView) {
            
            _datePickerView = [[BiDatePickerView alloc] initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, self.view.frame.size.height)];
            
            [_datePickerView setDateModeandButton];
            
            _datePickerView.delegate = self;
        }

        [self.view addSubview:_datePickerView];
        
    }
}

#pragma -mark Net Delegate
- (void)onNetEngineResponse:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
    
    NSDictionary * dict = (NSDictionary *)entity;
    
    [self showMessage:dict[@"result_info"]];
    
    sleep(1);
    
    if ([dict[@"response_status"] integerValue] != 200) {
        
        return;
        
    }
    
    BOOL isExist = NO;
    
    for (UIViewController * Vctrl in self.navigationController.viewControllers) {
        
        if ([Vctrl isKindOfClass:[BiSaleListViewController class]]) {
            
            isExist = YES;
            
            break;
        }
    }
    
    if (isExist) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
    
        BiSaleListViewController * listVc = [[BiSaleListViewController alloc] init];
        
        listVc.type = 1;
        
        [self.navigationController pushViewController:listVc animated:YES];
    }
    
    
}

- (void)onNetEngineResponseFail:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    [self removeHUDView:self];
    
}


@end
